﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;

namespace ShowDisplayElementControl
{
    /// <summary>
    /// Comparer of ShowDisplayElement objects by AirDate for ObjectiveListBox
    /// </summary>
    public class ItemComparerByDate : IComparer<Control>
    {
        int IComparer<Control>.Compare(Control x, Control y)
        {
            var d1 = new DateTime();
            var d2 = new DateTime();
            var a1 = ((ShowDisplayElement) x).AirDate;
            var a2 = ((ShowDisplayElement) y).AirDate;
            var sep = new[] { '/' };

            var d1R = DateTime.TryParse(a1, out d1);
            var d2R = DateTime.TryParse(a2, out d2);

            if (!d1R && a1 != "TBA")
            {
                var parts = a1.Split(sep);

                if (parts.Length > 0)
                {
                    if (int.Parse(parts[0]) < 1 || int.Parse(parts[0]) > 31)
                    {
                        parts[0] = "01";
                    }

                    var newDate = String.Join("/", parts);
                    DateTime.TryParse(newDate, out d1);
                } 
                else
                {
                    a1 = "TBA";    
                }
            }

            if (!d2R && a2 != "TBA")
            {
                var parts = a2.Split(sep);

                if (parts.Length > 0)
                {
                    if (int.Parse(parts[0]) < 1 || int.Parse(parts[0]) > 31)
                    {
                        parts[0] = "01";
                    }

                    var newDate = String.Join("/", parts);
                    DateTime.TryParse(newDate, out d2);
                }
                else
                {
                    a2 = "TBA";
                }
            }

            if (a1 == "TBA" && a2 == "TBA")
            {
                return String.Compare(((ShowDisplayElement)x).ShowName, ((ShowDisplayElement)y).ShowName);
            }
            
            if (a1 == "TBA" && a2 != "TBA")
            {
                return 1;
            }
            
            if (a1 != "TBA" && a2 == "TBA")
            {
                return -1;
            }
            
            return DateTime.Compare(d1, d2);
        }
    }
}